<template>
  <div style="display: flex;">
    <el-card
      class="box-card"
      style="width: 30%; margin-right: 30px;"
    >
      <div>
        <div style="text-align: center;">
          <img
            src="@/assets/paidaxing.jpeg"
            alt="头像"
            style="width: 120px; height: 120px; border-radius: 50%; margin-bottom: 10px;"
          />
          <div style="font-size: 20px; font-weight: bold;">
            {{ descData?.account }}
          </div>
          <div style="font-size: 16px; color: #666;">
            {{ descData?.nickname }}
          </div>
        </div>
      </div>
      <el-divider />
    </el-card>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>基本信息</span>
          <div style="text-align: right;">
            <el-button
              v-if="isEditing"
              type="info"
              @click="() => { isEditing = false }"
            >取消</el-button>
            <el-button
              type="primary"
              plain
              @click="toggleEdit"
            >{{ isEditing ? '保存' : '编辑' }}</el-button>
          </div>
        </div>
      </template>
      <el-descriptions
        :column="columnNum"
        :size="size"
        border
      >
        <!-- <template #extra>
          <el-button
            v-if="isEditing"
            type="info"
            @click="() => { isEditing = false }"
          >取消</el-button>
          <el-button
            type="primary"
            plain
            @click="toggleEdit"
          >{{ isEditing ? '保存' : '编辑' }}</el-button>
        </template> -->
        <el-descriptions-item
          v-for="(item, index) in descFields"
          :key="index"
          label-class-name="my-label"
          class-name="my-content"
          label-align="right"
        >
          <template #label>
            <div class="cell-item">
              <el-icon>
                <component :is="item.labelIcon" />
              </el-icon>
              {{ item.label }}
            </div>
          </template>
          <div v-if="isEditing && item.prop !== 'account' && item.prop !== 'gender' && item.prop !== 'password'">
            <el-input
              v-model="formData[item.prop]"
              size="default"
            />
          </div>
          <div v-else>
            <div v-if="item.contentType === 'tag'">
              <el-tag
                :type="item.tagMapper?.[descData?.[item.prop]]?.type"
                :key="item.prop"
                effect="light"
                size="default"
              >
                {{ item.tagMapper?.[descData?.[item.prop]]?.text }}
              </el-tag>
            </div>
            <div
              v-else
              style="display: flex;"
            >
              {{ item.formatter ? item.formatter(descData?.[item.prop]) : descData?.[item.prop] }}
              <div v-if="item.prop === 'password'">
                <el-button
                  text
                  type="primary"
                  size="small"
                  @click="updatePassword"
                  style="display: flex;"
                >
                  修改
                </el-button>
              </div>
            </div>
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>
  <FormDialog
    ref="passwordDialogRef"
    :formFields="passwordFields"
    :formHandlers="passwordHandlers"
  />
</template>
<script lang="ts" setup>
import { getUserProfileList, updateUserProfile, updateUserProfilePassword } from '@/api/user'
import { computed, onMounted, ref, reactive } from 'vue'
import { type DescField } from '@/common/type/field'
import { isResultSuccess } from '@/util/http'
import { ElMessage } from 'element-plus'
import { FormMode, GenderTagMapper } from '@/common/type/baseEnum'
import FormDialog from '@/components/FormDialog.vue'

const columnNum = ref(4)
const size = ref('large')
const descFields: Array<DescField> = [
  {
    label: '姓名',
    prop: 'account',
    labelIcon: 'user',
    itemWidth: 160,
  },
  {
    label: '性别',
    prop: 'gender',
    labelIcon: 'female',
    itemWidth: 160,
    contentType: 'tag',
    tagMapper: GenderTagMapper,
  },
  {
    label: '昵称',
    prop: 'nickname',
    labelIcon: 'userFilled',
    itemWidth: 160,
  },
  {
    label: '邮箱',
    prop: 'email',
    labelIcon: 'message',
    itemWidth: 160,
  },
  {
    label: '电话',
    prop: 'phone',
    labelIcon: 'phone',
  },
  {
    label: '密码',
    prop: 'password',
    labelIcon: 'lock',
    formatter: (value: string) => {
      return '已设置'
    }
  }
]

const passwordFields = [
  {
    label: '原密码',
    prop: 'oldPassword',
    formMeta: {
      isPwd: true,
      rules: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
      ],
    },
  },
  {
    label: '新密码',
    prop: 'newPassword',
    formMeta: {
      isPwd: true,
      rules: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
      ],
    }
  },
  {
    label: '确认密码',
    prop: 'confirmPassword',
    formMeta: {
      isPwd: true,
      rules: [
        { required: true, message: '请输入确认密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            const passwordValue = passwordDialogRef.value?.form?.data?.newPassword  // 通过对话框引用获取密码值
            return value !== passwordValue ? callback(new Error('两次输入密码不一致')) : callback()
          }
        }
      ]
    }
  }
]

const passwordDialogRef = ref()
const descData = ref()

onMounted(async () => {
  try {
    const res = await getUserProfileList()
    if (res && isResultSuccess(res)) {
      descData.value = res.data
    }
    console.log(res.data)
  } catch (err) {
    ElMessage.error('获取用户信息失败！' + err.response.data.msg)
  }
})

const isEditing = ref(false)
const formData = reactive({}) // 新增表单数据对象
const toggleEdit = async () => {
  if (isEditing.value) {
    try {
      const res = await updateUserProfile(formData)
      if (res && isResultSuccess(res)) {
        Object.assign(descData.value, formData)
        ElMessage.success('保存成功')
      }
    } catch (err) {
      ElMessage.error('保存失败：' + err.response.data.msg)
    }
  } else {
    Object.assign(formData, descData.value)
  }
  isEditing.value = !isEditing.value
}


const passwordHandlers = new Map([
  [FormMode.Edit, updateUserProfilePassword],
])
const updatePassword = () => {
  passwordDialogRef.value.open(FormMode.Edit)
  // try {
  //   const res = await updateUserProfilePassword(formData)  
  //   if (res && isResultSuccess(res)) {
  //     ElMessage.success('修改密码成功')
  //   }
  // }catch (err) {
  //   ElMessage.error('修改密码失败：' + err.response.data.msg)
  // }
}
</script>
<style scoped>
/* .el-descriptions {
  margin-top: 20px;
} */

.cell-item {
  display: flex;
  align-items: center;
  /* text-align: right; */
  padding: auto auto;

  .el-icon {
    margin: auto auto;
    margin-right: 8px;
  }
}

:deep(.my-label) {
  width: 100px;
}

:deep(.my-content) {
  width: 200px;
  height: 60px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  /* text-align: right; */
  align-items: center;
}

.text {
  font-size: 14px;
}

.box-card {
  margin-top: 12px;
  border-radius: 12px;
}
</style>
